package cn.ichiva.common.jwt.impl;

import cn.ichiva.common.jwt.JWTBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Date;
import java.util.UUID;

public class DefaultJWTBuilder implements JWTBuilder {
    public final PrivateKey privateKey;

    public DefaultJWTBuilder(String path) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
        this(Files.readAllBytes(Paths.get(path)));
    }

    public DefaultJWTBuilder(PrivateKey privateKey) {
        this.privateKey = privateKey;
    }

    public DefaultJWTBuilder(byte[] privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
        this.privateKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privateKey));
    }

    @Override
    public String build(String text,long expire) {
        if(expire < 1) expire = 24 * 3600 * 1000;
        return Jwts.builder()
                .claim("TEXT",text)
                .setId(UUID.randomUUID().toString())
                .setExpiration(new Date(System.currentTimeMillis() + expire))
                .signWith(privateKey, SignatureAlgorithm.RS256)
                .compact();
    }
}
